<script>
import { getExportTemplate, uploadExcelAPI } from '@/api/employeeApi'
import FileSaver from 'file-saver'

export default {
  name: 'importExcel',
  props: {
    visibleExcel: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    /* 弹框关闭时的回调函数 */
    handleClose() {
      this.$emit('update:visibleExcel', false)
    },
    /* 点击下载模板按钮的回调函数 */
    async handleDownload() {
      const template = await getExportTemplate()
      FileSaver.saveAs(template, '员工导入模板.xlsx')
    },
    /* 点击上传按钮的回调函数 */
    handleUpload() {
      // 打开windows的弹框让用户选择文件上传
      this.$refs.file.click()
    },
    /* 文件选择框的change事件 */
    async uploadChange(event) {
      try {
        const file = event.target.files
        if (file.length <= 0) return
        const formData = new FormData()
        formData.append('file', file[0])
        const { message } = await uploadExcelAPI(formData)
        this.$message.success(message)
        this.$emit('uploadSuccess')
        this.$emit('update:visibleExcel', false)
      } catch (e) {
        this.$message.error(e.message)
      } finally {
        this.$refs.file.value = ''
      }
    }
  }

}
</script>

<template>
  <el-dialog title="导入员工" :visible="visibleExcel" append-to-body :close-on-click-modal="false" @close="handleClose">
    <div class="upload">
      <input type="file" accept=".xlsx,.xls" ref="file" @change="uploadChange"></input>
      <i class="el-icon-upload"></i>
      <span class="download" @click="handleDownload">下载模板</span>
      <el-button type="primary" @click="handleUpload">点击上传</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 60%;
  border: 2px dashed #ccc;
  margin: 0 auto;
  padding: 30px 0;

  input {
    display: none;
  }

  i {
    font-size: 50px;
  }

  .download {
    font-size: 16px;
    color: #409eff;
    font-weight: 600;
    margin: 15px 0;
    cursor: pointer;
  }

  .text {
    font-size: 20px;
    color: #ccc;
    font-weight: 500;

  }

  .el-button {
    margin-left: 10px;
  }
}
</style>
